﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MultLanguage.ConfigFile
{
    /// <summary>
    /// 多语言配置文件
    /// </summary>
    public class MLConfigFile : IDisposable
    {
        private string _strError = "";
        public string ErrorMessage
        {
            get
            {
                return _strError;
            }
        }

        private ExeConfigurationFileMap file;
        private string ConfigFilePath = "MultLanguage//Language_en.xml";
        private Configuration _config;

        /// <summary>
        /// 存储在内存中的所有双语节点
        /// </summary>
        private Dictionary<string, string> _collection = new Dictionary<string, string>();

        public Dictionary<string, string> Collection
        {
            get { return _collection; }
        }

        public MLConfigFile()
        {
         
        }
        /// <summary>
        /// 新建或打开文件
        /// </summary>
        /// <param name="strFilePath">文件名</param>
        public MLConfigFile(string strFilePath)
        {
            ConfigFilePath = strFilePath;
        }

        public bool Init()
        {
            try
            {            
                file = new ExeConfigurationFileMap();
                file.ExeConfigFilename = ConfigFilePath;
                bool bExists = File.Exists(ConfigFilePath);
                _config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
                if (!bExists)
                {
                    AddBilingualSection();
                    Save();
                }
                else
                {
                    LoadPairs();
                }
                return true;
            }
            catch (Exception ex)
            {
                _strError = ex.ToString();
                return false;
            }
        }

        public void InitData(List<LanguagePair> list)
        {
            BilingualSection section = _config.GetSection("BilingualSection") as BilingualSection;
            BilingualCollection collection = section.Pairs;
            collection.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                BilingualElement item = collection[list[i].CHN];
                if (item == null)
                {
                    collection.Add(new BilingualElement(list[i].ID, list[i].CHN, list[i].FOL));
                }
                else
                {
                    collection[list[i].CHN].FOL = list[i].FOL;
                }
            }
            Save();
            LoadPairs();
        }

        private void AddBilingualSection()
        {
            _config.Sections.Add("BilingualSection", new BilingualSection());
        }

        /// <summary>
        /// 写入一个双语子项节点
        /// </summary>
        /// <param name="first"></param>
        /// <param name="second"></param>
        public void Add(int id, string first, string second)
        {
            BilingualSection section = _config.GetSection("BilingualSection") as BilingualSection;
            BilingualElement item = section.Pairs[first];
            if (item == null)
            {
                section.Pairs.Add(new BilingualElement(id, first, second));
            }
            else
            {
                section.Pairs[first].FOL = second;
            }
        }

        /// <summary>
        /// 移除一个双语子项节点
        /// </summary>
        /// <param name="key">关键词</param>
        public void Remove(string key)
        {
            BilingualSection section = _config.GetSection("BilingualSection") as BilingualSection;
            BilingualElement item = section.Pairs[key];
            if (item != null)
            {
                section.Pairs.Remove(key);
            }
        }

        /// <summary>
        /// 获取保存的双语言条目列表
        /// </summary>
        /// <returns></returns>
        public void LoadPairs()
        {
            try 
            {
                _collection.Clear();
                BilingualSection section = _config.GetSection("BilingualSection") as BilingualSection;
                BilingualCollection pairs = section.Pairs;
                int nCount = pairs.Count;            
                for (int i = 0; i < nCount; ++i)
                {
                    string strKey = pairs[i].CHN;
                    string strValue = pairs[i].FOL;                 
                    if (strValue.Contains("\\n"))
                    {
                        strValue = strValue.Replace("\\n", "\n");
                    }
                    _collection.Add(strKey, strValue);
                }
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.ToString());
            }          
        }

        public string GetForeignLanguage(string chn)
        {
            if (_collection.ContainsKey(chn))
            {
                return _collection[chn];
            }
            else
            {
                BilingualSection section = _config.GetSection("BilingualSection") as BilingualSection;
                BilingualElement item = section.Pairs[chn];
                if(item != null)
                {
                    return item.FOL;
                }
                else
                {
                    return "";
                }                
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public void Save()
        {
            _config.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("BilingualSection");
            LoadPairs();
        }

        public void Dispose()
        {
            _collection.Clear();
        }
    }
}
